What is an Array?
An array is a type of linear data structure where elements are stored in a sequence. All elements in an array are of the same type and are stored next to each other in memory.
Array Representation in Data Structures
The representation of an array is defined by its declaration, which means allocating memory for an array of a specified size.
Array Declaration
Arrays can be declared in various ways in different programming languages. Here are some examples:
C++
int arr[5]; // Array to store integers
char arr[10]; // Array to store characters
float arr[20]; // Array to store floats
C
int arr[5]; // Array to store integers
char arr[10]; // Array to store characters
float arr[20]; // Array to store floats
Java
int[] arr = new int[5]; // Array to store integers
char[] arr = new char[10]; // Array to store characters
float[] arr = new float[20]; // Array to store floats
Python
arr = [None] * 5 // Array to store any data type, initialized with None
arr = [0] * 10 // Array to store integers, initialized with 0
arr = [''] * 20 // Array to store characters, initialized with empty strings
Static Memory Allocation
The above declarations are examples of static or compile-time memory allocation. This means that the array's memory is allocated when the program is compiled. Here, a fixed size of memory (specified in the square brackets []) is allocated for storage.
However, this approach has limitations:
- If the array is declared larger than needed, memory is wasted.
- If the array is declared smaller than needed, there won't be enough memory to store all elements.
In situations where the size of the array is not known in advance, static memory allocation is not ideal.
Types of Arrays
There are majorly three types of arrays:
- One-dimensional array (1-D arrays)
- Two-dimensional (2D) array
- Three-dimensional array
1. One-dimensional array (1-D arrays):
You can imagine a 1D array as a row, where elements are stored one after another.
Syntax for Declaration of Single Dimensional Array:
data_type array_name[array_size];
where,
- data_type: is a type of data of each array block.
- array_name: is the name of the array using which we can refer to it.
- array_size: is the number of blocks of memory array going to have.
For Example:
int nums[5];
2. Two-dimensional (2D) array:
Multidimensional arrays can be considered as an array of arrays or as a matrix consisting of rows and columns.
Syntax for Declaration of Two-Dimensional Array:
data_type array_name[sizeof_1st_dimension][sizeof_2nd_dimension];
where,
- data_type: is a type of data of each array block.
- array_name: is the name of the array using which we can refer to it.
- sizeof_dimension: is the number of blocks of memory array going to have in the corresponding dimension.
For Example:
int nums[5][10];
3. Three-dimensional array:
A 3-D Multidimensional array contains three dimensions, so it can be considered an array of two-dimensional arrays.
Syntax for Declaration of Three-Dimensional Array:
data_type array_name[sizeof_1st_dimension][sizeof_2nd_dimension][sizeof_3rd_dimension];
where,
- data_type: is a type of data of each array block.
- array_name: is the name of the array using which we can refer to it.
- sizeof_dimension: is the number of blocks of memory array going to have in the corresponding dimension.
For Example:
int nums[5][10][2];
Different ways of accessing array elements | Array Operations
In this article, two unique and different ways of accessing an element from an array rather than the conventional
arr[i]
expression are discussed below.
- Using pointer
*(arr+1)
- Using a little manipulation
i[arr]
for using arrays and the reason behind that.
The below example is another simplest way of accessing array elements in C++.
#include <iostream>
using namespace std;
int main()
{
double num[] = { 11, 12, 13, 14, 15, 16 };
double add = 0;
double count = 0;
double avg;
cout << "The number is=";
for (const double& n : num) {
cout << n << " " <<endl;
add += n;
++count;
}
cout << "Addition of numbers= " << add << endl;
avg = add / count;
cout << "average of numbers= " << avg << endl;
return 0;
}
Output
The number is=11
12
13
14
15
16
Addition of numbers= 81
average of numbers= 13.5
Example:
int a[10];
gets stored like:
- *(a) - which points to the first element.
- *(a+1) - which points to the second element.
- Similarly, we can have the last element pointed by
*(a+(n-1)) where n-1 is used as arrays in C++ have zero-based indexing.
Using this concept let us discuss the first method of accessing the arrays:
Using the concept of pointers
Below is the C++ program to implement the above concept:
// C++ program to demonstrate the above approach
#include <iostream>
using namespace std;
// Driver Code
int main()
{
int arr[10];
// Conventional method
// for(int i = 0; i<10; i++)
//{
// arr[i] = i+1;
//}
// Pointer Method
for (int i = 0; i < 10; i++) {
*(arr + i) = i + 1;
}
cout << "Values : ";
for (int i = 0; i < 10; i++) {
cout << *(arr + i) << ' ';
}
return 0;
}
Output
Values : 1 2 3 4 5 6 7 8 9 10
Inserting Elements in an Array | Array Operations
In this post, we will look into insertion operations in an array, i.e., how to insert elements into an array, such as:
1. Inserting Elements in an Array at the End:
In an unsorted array, the insert operation is faster as compared to a sorted array because we don’t have to care about the position at which the element is to be placed.
// C++ program to insert an element at the end
#include <bits/stdc++.h>
using namespace std;
// Function to insert a key into an array
int insertSorted(int arr[], int n, int key, int capacity) {
// Check if the array is already full
if (n >= capacity)
return n;
// Add the key at the end of the array
arr[n] = key;
// Return the updated size of the array
return (n + 1);
}
int main() {
int arr[20] = {12, 16, 20, 40, 50, 70};
int capacity = sizeof(arr) / sizeof(arr[0]);
int n = 6;
int i, key = 26;
cout << "\nBefore Insertion: ";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
// Inserting the key into the array
n = insertSorted(arr, n, key, capacity);
cout << "\nAfter Insertion: ";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Output
Before Insertion: 12 16 20 40 50 70
After Insertion: 12 16 20 40 50 70 26
Time Complexity: O(n)
Auxiliary Space: O(1)
2. Inserting Elements in an Array at any Position:
Insert operation in an array at any position can be performed by shifting elements to the right, which are on the right side of the required position.
// C++ Program to insert an element at a specific position
#include <bits/stdc++.h>
using namespace std;
// Function to insert element at a specific position
void insertElement(int arr[], int n, int x, int pos) {
// Shift elements to the right
for (int i = n - 1; i >= pos; i--)
arr[i + 1] = arr[i];
arr[pos] = x;
}
int main() {
int arr[15] = {2, 4, 1, 8, 5};
int n = 5;
cout << "Before insertion: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
int x = 10, pos = 2;
// Function call
insertElement(arr, n, x, pos);
n++;
cout << "After insertion: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Output
Before insertion: 2 4 1 8 5
After insertion: 2 4 10 1 8 5
Time Complexity: O(N)
Auxiliary Space: O(1)
3. Inserting Elements in a Sorted Array:
In a sorted array, a search operation is performed for the possible position of the given element by using Binary search, and then an insert operation is performed followed by shifting the elements. In an unsorted array, the insert operation is faster as compared to the sorted array because we don’t have to care about the position at which the element is placed.
// C program to insert an element in a sorted array
#include <stdio.h>
// Function to insert a key in a sorted array
int insertSorted(int arr[], int n, int key, int capacity) {
// Check if the array is already full
if (n >= capacity)
return n;
int i;
for (i = n - 1; (i >= 0 && arr[i] > key); i--)
arr[i + 1] = arr[i];
arr[i + 1] = key;
return (n + 1);
}
int main() {
int arr[20] = {12, 16, 20, 40, 50, 70};
int capacity = sizeof(arr) / sizeof(arr[0]);
int n = 6;
int i, key = 26;
printf("\nBefore Insertion: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
// Function call
n = insertSorted(arr, n, key, capacity);
printf("\nAfter Insertion: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
Before Insertion: 12 16 20 40 50 70
After Insertion: 12 16 20 26 40 50 70
Time Complexity: O(N) [In the worst case all elements may have to be moved]
Auxiliary Space: O(1)
Deleting Elements in an Array | Array Operations
Last Updated: 21 Jul, 2023
In this post, we will look into deletion operation in an Array, i.e., how to delete an element from an Array, such as:
Deleting Elements in an Array when it is Unsorted
In the delete operation, the element to be deleted is searched using linear search, and then the delete operation is performed followed by shifting the elements.
// C++ program to implement delete operation in a
// unsorted array
#include <iostream>
using namespace std;
// To search a key to be deleted
int findElement(int arr[], int n, int key);
// Function to delete an element
int deleteElement(int arr[], int n, int key)
{
// Find position of element to be deleted
int pos = findElement(arr, n, key);
if (pos == -1) {
cout << "Element not found";
return n;
}
// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];
return n - 1;
}
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
return -1;
}
// Driver's code
int main()
{
int i;
int arr[] = { 10, 50, 30, 40, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
cout << "Array before deletion\n";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
// Function call
n = deleteElement(arr, n, key);
cout << "\n\nArray after deletion\n";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
Array before deletion
10 50 30 40 20
Array after deletion
10 50 40 20
Time Complexity: O(N)
Auxiliary Space: O(1)
Deleting Elements in an Array when it is Sorted
In the delete operation, the element to be deleted is searched using binary search, and then the delete operation is performed followed by shifting the elements.
// C++ program to implement delete operation in a
// sorted array
#include <bits/stdc++.h>
using namespace std;
// To search a key to be deleted
int binarySearch(int arr[], int low, int high, int key);
/* Function to delete an element */
int deleteElement(int arr[], int n, int key)
{
// Find position of element to be deleted
int pos = binarySearch(arr, 0, n - 1, key);
if (pos == -1) {
cout << "Element not found";
return n;
}
// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];
return n - 1;
}
int binarySearch(int arr[], int low, int high, int key)
{
if (high < low)
return -1;
int mid = (low + high) / 2;
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}
// Driver code
int main()
{
int i;
int arr[] = { 10, 20, 30, 40, 50 };
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
cout << "Array before deletion\n";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
// Function call
n = deleteElement(arr, n, key);
cout << "\n\nArray after deletion\n";
for (i = 0; i < n; i++)
cout << arr[i] << " ";
}
Output:
Array before deletion
10 20 30 40 50
Array after deletion
10 20 40 50
Time Complexity: O(N). In the worst case, all elements may have to be moved.
Auxiliary Space: O(log N). An implicit stack will be used.
Searching Elements in an Array | Array Operations
In this post, we will look into search operations in an array, i.e., how to search for an element in an array using various techniques:
Searching operations in an Unsorted Array using Linear Search
In an unsorted array, the search operation can be performed by linear traversal from the first element to the last element, i.e., Linear Search
Coding implementation of the search operation:
// C++ program to implement linear
// search in unsorted array
#include <bits/stdc++.h>
using namespace std;
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Driver's Code
int main()
{
int arr[] = { 12, 34, 10, 6, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
// Using a last element as search element
int key = 40;
// Function call
int position = findElement(arr, n, key);
if (position == -1)
cout << "Element not found";
else
cout << "Element Found at Position: "
<< position + 1;
return 0;
}
Output:
Element Found at Position: 5
Time Complexity: O(N)
Auxiliary Space: O(1)
Searching in a Sorted Array using Linear Search
In a sorted array, the most trivial method for the search operation is by using Linear Search.
Search Operation in a sorted array
// C++ program to implement linear
// search in sorted array
#include <bits/stdc++.h>
using namespace std;
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
// If the key is not found
return -1;
}
// Driver's Code
int main()
{
int arr[] = { 5, 6, 7, 8, 9, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
// Using a last element as search element
int key = 10;
// Function call
int position = findElement(arr, n, key);
if (position == -1)
cout << "Element not found";
else
cout << "Element Found at Position: "
<< position + 1;
return 0;
}
Output:
Element Found at Position: 6
Time Complexity: O(N)
Auxiliary Space: O(1)
Searching in a Sorted Array using Binary Search
In a sorted array, the search operation can be performed efficiently by using binary search.
Search Operation in a sorted array
// C++ program to implement binary search in sorted array
#include <bits/stdc++.h>
using namespace std;
int binarySearch(int arr[], int low, int high, int key)
{
if (high < low)
return -1;
int mid = (low + high) / 2; /*low + (high - low)/2;*/
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}
/* Driver code */
int main()
{
// Let us search 3 in below array
int arr[] = { 5, 6, 7, 8, 9, 10 };
int n, key;
n = sizeof(arr) / sizeof(arr[0]);
key = 10;
// Function call
cout << "Index: " << binarySearch(arr, 0, n - 1, key)
<< endl;
return 0;
}
Output:
Index: 5
Time Complexity: O(log(n)) Using Binary Search
Auxiliary Space: O(log(n)) due to recursive calls, otherwise iterative version uses Auxiliary Space of O(1).
Searching in a Sorted Array using Fibonacci Search
Fibonacci Search is a comparison-based technique that uses Fibonacci numbers to search an element in a sorted array.
// C++ program of the above approach
#include <iostream>
#include <vector>
using std::cout;
// Utility function to find minimum of two elements
int minimum(int x, int y) { return (x < y) ? x : y; }
/* Returns index of x if present, else returns -1 */
int fibonacciSearch(int arr[], int x, int n)
{
/* Initialize fibonacci numbers */
int fibMMm2 = 0; // (m-2)'th Fibonacci No.
int fibMMm1 = 1; // (m-1)'th Fibonacci No.
int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci
/* fibM is going to store the smallest Fibonacci
Number greater than or equal to n */
while (fibM < n) {
fibMMm2 = fibMMm1;
fibMMm1 = fibM;
fibM = fibMMm2 + fibMMm1;
}
// Marks the eliminated range from front
int offset = -1;
/* while there are elements to be inspected. Note that
we compare arr[fibMm2] with x. When fibM becomes 1,
fibMm2 becomes 0 */
while (fibM > 1) {
// Check if fibMm2 is a valid location
int i = minimum(offset + fibMMm2, n - 1);
/* If x is greater than the value at index fibMm2,
cut the subarray array from offset to i */
if (arr[i] < x) {
fibM = fibMMm1;
fibMMm1 = fibMMm2;
fibMMm2 = fibM - fibMMm1;
offset = i;
}
/* If x is greater than the value at index fibMm2,
cut the subarray after i+1 */
else if (arr[i] > x) {
fibM = fibMMm2;
fibMMm1 = fibMMm1 - fibMMm2;
fibMMm2 = fibM - fibMMm1;
}
/* element found. return index */
else
return i;
}
/* comparing the last element with x */
if (fibMMm1 && arr[offset + 1] == x)
return offset + 1;
/*element not found. return -1 */
return -1;
}
// Driver Code
int main()
{
int arr[] = { 10, 22, 35, 40, 45, 50,
80, 82, 85, 90, 100, 235 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 235;
int ind = fibonacciSearch(arr, x, n);
if (ind >= 0)
cout << "Found at index: " << ind;
else
cout << x << " isn't present in the array";
return 0;
}
Output:
Found at index: 11
Time Complexity: O(log(n)) Using Fibonacci Search
Auxiliary Space: O(1) Using Fibonacci Search
Introduction to Matrix or Grid Data Structure – Two Dimensional Array
Matrix or Grid is a two-dimensional array mostly used in mathematical and scientific calculations. It is also considered as an array of arrays, where each array at every index has the same size. In this article, we will cover all the basics of Matrix, the Operations on Matrix, its implementation, advantages, disadvantages which will help you solve all the problems based on Matrix Data Structure.
What is a Matrix Data Structure?
Matrix Data Structure is a two-dimensional array that consists of rows and columns. It is an arrangement of elements in horizontal or vertical lines of entries. It is also considered as an array of arrays, where each array at each index has the same size.
Declaration of Matrix Data Structure:
#include <iostream>
using namespace std;
int main()
{
// Defining number of rows and columns in matrix
int number_of_rows = 3, number_of_columns = 3;
// Array Declaration
int arr[number_of_rows][number_of_columns];
return 0;
}
Initializing Matrix Data Structure:
#include <iostream>
using namespace std;
int main() {
// Initializing a 2-D array with values
int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
return 0;
}
Operations on Matrix Data Structure:
- Access elements of Matrix Data Structure:
#include <iostream>
using namespace std;
int main()
{
// Initializing a 2-D array with values
int arr[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// Accessing elements of 2-D array
cout << "First element of first row: " << arr[0][0] << "\n";
cout << "Third element of second row: " << arr[1][2] << "\n";
cout << "Second element of third row: " << arr[2][1] << "\n";
return 0;
}
- Traversal of a Matrix Data Structure:
#include <iostream>
using namespace std;
int main()
{
int arr[3][4] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
// Traversing over all the rows
for (int i = 0; i < 3; i++) {
// Traversing over all the columns of each row
for (int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
- Searching in a Matrix Data Structure:
#include <bits/stdc++.h>
using namespace std;
bool searchInMatrix(vector<vector<int>>& arr, int x)
{
int m = arr.size(), n = arr[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == x)
return true;
}
}
return false;
}
// Driver program to test above
int main()
{
int x = 8;
vector<vector<int>> arr
= { { 0, 6, 8, 9, 11 },
{ 20, 22, 28, 29, 31 },
{ 36, 38, 50, 61, 63 },
{ 64, 66, 100, 122, 128 } };
if (searchInMatrix(arr, x))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
- Sorting Matrix Data Structure:
We can sort a matrix row-wise or column-wise.
Applications of Matrix Data Structure:
- In Algorithms: Used in problems based on Dynamic Programming Algorithm to store answers to computed states.
- Image processing: Represent images as a matrix of pixels for operations.
- Robotics: Represent positions and orientations of robots and end-effectors.
- Transportation and logistics: Represent transportation networks and solve optimization problems.
- Finance: Represent portfolios, calculate risk and return of investments.
- Linear Algebra: Used to represent linear equations and solve systems of equations.
Advantages of Matrix Data Structure:
- Facilitates 2D visualization.
- Stores multiple elements of the same type using the same name.
- Allows random access to items.
- Stores fixed-size data efficiently.
- Relatively easy to implement.
Disadvantages of Matrix Data Structure:
- Space inefficient when storing few elements.
- Requires predefined size.
- Costly insertion and deletion operations if shifting is involved.
- Resizing is time-consuming.
How to Iterate a Multidimensional Array?
Multidimensional arrays are arrays that have more than one dimension. For example, a simple array is a 1-D array, a matrix is a 2-D array, and a cube or cuboid is a 3-D array. Visualizing arrays with more than 3 dimensions involves thinking of them as collections of arrays of lower dimensions:
n-D array = Collection of (n-1)D arrays
For example, a matrix or 2-D array is a collection of 1-D arrays.
How to Iterate over elements of a Multidimensional array?
It can be observed that only a 1-D array contains elements, and a multidimensional array contains smaller dimension arrays. Hence, first iterate over the smaller dimension array and iterate over the 1-D array inside it. Doing this for the whole multidimensional array will iterate over all elements of the multidimensional array.
Example 1: Iterating over a 2-D array
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Considering 2-D array having 3 rows and 3 columns
int n = 3;
int m = 3;
int arr[][3]
= { { 3, 2, 7 }, { 2, 6, 8 }, { 5, 1, 9 } };
// Iterating over all 1-D arrays in 2-D array
for (int i = 0; i < n; i++) {
// Printing all elements in ith 1-D array
for (int j = 0; j < m; j++) {
// Printing jth element of ith row
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output:
3 2 7
2 6 8
5 1 9
Time Complexity: O(n*m)
Auxiliary Space: O(1)
Example 2: Iterating over a 3-D array
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Consider 3-D array of dimensions 2*2*2
int x = 2, y = 2, z = 2;
int arr[][3][2] = { { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };
// Iterating over each 2-D array in 3-D array
for (int i = 0; i < x; i++) {
cout << "Inside " << i + 1
<< " 2D array in 3-D array" << endl;
// Iterating over each 1-D array
for (int j = 0; j < y; j++) {
cout << "Inside " << j + 1
<< " 1D array of the 2-D array" << endl;
// Iterating over each element in 1-D array
for (int k = 0; k < z; k++) {
cout << arr[i][j][k] << " ";
}
cout << endl;
}
cout << endl;
}
return 0;
}
Output:
Inside 1 2D array in 3-D array
Inside 1 1D array of the 2-D array
1 2
Inside 2 1D array of the 2-D array
3 4
Inside 2 2D array in 3-D array
Inside 1 1D array of the 2-D array
5 6
Inside 2 1D array of the 2-D array
7 8
Time Complexity: O(x*y*z)
Auxiliary Space: O(1)